/**
 * 
 */
package com.sad.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhaoqy
 *
 */
public class PropertiesHolder {
	private static final Logger logger = LoggerFactory.getLogger(PropertiesHolder.class);

	// Properties Cache
	public static Map<String, Properties> pMap = new Hashtable<String, Properties>();

	/**
	 * Set properties to properties cache
	 * 
	 * @param pName
	 * @throws IOException
	 */
	public static void setProperties(String pName) throws IOException {

		Properties properties = new Properties();
		InputStream is = null;

		try {
			is = PropertiesHolder.class.getResourceAsStream(pName);
			properties.load(is);

		} finally {

			if (is != null) {
				is.close();
			}

		}

		logger.info("Load to properties cache : " + pName);
		pMap.put(pName, properties);
	}

	/**
	 * Get properties by properties path
	 * 
	 * @param pName
	 * @return
	 */
	public static Properties getProperties(String pName) {
		return pMap.get(pName);
	}

	/**
	 * Get properties value by properties path & key
	 * 
	 * @param pName
	 * @param key
	 * @return
	 */
	public static String getPropertiesValue(String pName, String key) {
		if (pMap.get(pName) == null) {
			return "";
		}

		return pMap.get(pName).getProperty(key);
	}
	
	/**
	 * Get properties value by properties path & key
	 * 
	 * @param pName
	 * @param key
	 * @return
	 */
	public static String getPropertiesValue(String pName, String key,String defaultValue) {
		if (pMap.get(pName) == null || "".equals(pMap.get(pName).getProperty(key).trim())) {
			return defaultValue;
		}

		return pMap.get(pName).getProperty(key);
	}
	
	/**
	 * 
	 * @param pName
	 * @param key
	 * @return
	 */
	public static int getPropertiesIntValue(String pName, String key,int defalut) {
		if (pMap.get(pName) == null || "".equals(pMap.get(pName).getProperty(key).trim())) {
			return defalut;
		}
		
		String v = getPropertiesValue(pName,key);
		int value = 0;
		try{
			value = Integer.valueOf(v).intValue();
		}catch(Exception e){
			value = defalut;
		}
		
		return value;
	}
	
}
